package common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class UserTokenFrequency {

    private final String user;

    private final Map<String, Integer> tokenFreqs;

    private final double averageFreq;

    public UserTokenFrequency(String user, List<TokenCount> tokens) {
        this.user = user;

        tokenFreqs = new HashMap<String, Integer>();
        double sumFreqSquare = 0;
        for (final TokenCount token : tokens) {
            tokenFreqs.put(token.getToken(), token.getCount());
            sumFreqSquare = sumFreqSquare + token.getCount() * token.getCount();
        }

        averageFreq = Math.sqrt(sumFreqSquare);
    }

    public String getUser() {
        return user;
    }

    public double similarityScore(UserTokenFrequency other) {
        double nominator = 0;
        for (final Entry<String, Integer> entry : tokenFreqs.entrySet()) {
            if (other.tokenFreqs.containsKey(entry.getKey())) {
                nominator = nominator + this.tokenFreqs.get(entry.getKey()) * other.tokenFreqs.get(entry.getKey());
            }
        }

        return nominator / (this.averageFreq * other.averageFreq);
    }

}
